package com.njlime.cms.repository.sys;

import com.njlime.cms.entities.Label;
import com.njlime.core.base.repository.impl.BaseDaoImpl;
import com.njlime.core.helper.PageBean;
import com.njlime.core.utils.StringUtil;
import com.njlime.sys.security.util.UserUtils;
import org.springframework.stereotype.Repository;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Dean on 2017/8/11.
 */
@Repository
public class LabelDaoImpl extends BaseDaoImpl<Label> {


    /**
     * 根据名称查询
     * @param name
     * @param unit_id
     * @return
     */
    public Label getByName(String name, int unit_id){
        StringBuilder sb = new StringBuilder();
        List<Object> arrList = new ArrayList<Object>();
        sb.append("select * from t_label where name = ? and unit_id = ? and is_del = 0 ");
        arrList.add(name);
        arrList.add(unit_id);
        return findOne(sb.toString(),arrList);
    }

    /**
     * 更新
     *
     * @param label
     * @return
     */
    public int editLabel(Label label) {
        StringBuilder sb = new StringBuilder();
        List<Object> arrList = new ArrayList<Object>();
        sb.append("UPDATE t_label SET update_time = now(),updater = ? ");
        arrList.add(label.getUpdater());
        if(!StringUtil.isEmpty(label.getName())){
            sb.append(",name = ? ");
            arrList.add(label.getName());
        }
        sb.append(" where id = ?");
        arrList.add(label.getId());
        return updateJdbc(sb.toString(), arrList);
    }

    /**
     * 删除
     *
     * @param id
     * @return
     */

    public int del(int id) {
        StringBuilder sb = new StringBuilder();
        List<Object> arrList = new ArrayList<Object>();
        sb.append("update t_label set is_del = 1 where id = ? ");
        arrList.add(id);
        return updateJdbc(sb.toString(), arrList);
    }


    /**
     * 获取列表
     *
     * @param pageBean
     * @return
     */
    public PageBean list(PageBean pageBean, Label label) {
        StringBuilder sb = new StringBuilder();
        List<Object> arrList = new ArrayList<Object>();
        sb.append("select t.* from t_label t ");
        sb.append("left join t_unit u on u.id = t.unit_id ");
        sb.append("where t.is_del = 0 ");
        if(!StringUtil.isEmpty(label.getName())){
            sb.append("and t.name = ? ");
            arrList.add(label.getName());
        }
        dataScopeFilter(UserUtils.getUser().getId(), sb, arrList, "u", "t");
        int num = getListJdbcSize(sb.toString(), arrList);
        pageBean.setTotalCount(num);
        pageBean.setTotalPage(pageBean.getTotalPage());
        if (num > 0) {
            sb.append(" order by t.id desc limit ?,?");
            arrList.add((pageBean.getCurPage() - 1) * pageBean.getPageSize());
            arrList.add(pageBean.getPageSize());
            pageBean.setMapList(getListJdbc(sb.toString(), arrList));
        }
        return pageBean;
    }
}
